﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana
{
    /// <summary>
    /// 用于根据所有Variable的值，做并行、选择值判断，来作激活，渐变对象动画
    /// 需要变化的对象，直接绑定variable变量值，而不需要通过脚本控制。
    /// </summary>
    [AddComponentMenu("Nirvana/UI/Bind/Variable Bind Active")]
    public sealed class UIVariableBindActive : UIVariableBindBool
    {
        public enum TransitionMode
        {
            /// <summary>
            /// 立即过度
            /// </summary>
            Instant,
            /// <summary>
            /// 渐变过度
            /// </summary>
            Fade
        }
        [HideInInspector]
        [SerializeField]
        private TransitionMode transitionMode = TransitionMode.Instant;
        [HideInInspector]
        [SerializeField]
        private float transitionTime = 0.1f;
        /// <summary>
        /// 用于渐变过度透明度
        /// </summary>
        private CanvasGroup m_canvasgroup;

        protected override void OnValueChanged()
        {
            bool result = base.GetResult();
            if (this.transitionMode == TransitionMode.Instant) this.gameObject.SetActive(result);
            else
            {
                if(m_canvasgroup == null)
                {
                    this.m_canvasgroup = this.gameObject.GetComponent<CanvasGroup>();
                }
                if(m_canvasgroup != null)
                {
                    this.gameObject.SetActive(true);
                    if (this.gameObject.activeInHierarchy)
                    {
                        this.StopAllCoroutines();
                        if (result) this.StartCoroutine(ToFade(this.m_canvasgroup,1f,true));
                        else this.StartCoroutine(ToFade(this.m_canvasgroup, 0f, false));
                    }
                    else
                    {
                        this.gameObject.SetActive(result);
                    }
                }
                else
                {
                    this.gameObject.SetActive(result);
                }
            }
        }

        private IEnumerator ToFade(CanvasGroup canvasGroup,float alpha,bool isActive)
        {
            float _transTime = this.transitionTime;
            while(_transTime > 0)
            {
                yield return null;
                _transTime -= Time.deltaTime;
                canvasGroup.alpha = Mathf.Lerp(canvasGroup.alpha, alpha, 1f - _transTime / this.transitionTime);
            }

            canvasGroup.gameObject.SetActive(isActive);
            yield break;
        }


    }
}

